package com.app.micaihu.view.army.presenter

import com.app.base.mvp.BasePresenter
import com.app.http.NetRequestListener
import com.app.http.bean.BaseBean
import com.app.micaihu.configure.LoadType
import com.app.micaihu.manager.UserInforManager
import com.app.micaihu.utils.ApiServiceUtils.apiService
import com.app.micaihu.utils.ParamsMapUtils
import com.app.micaihu.view.army.contract.ArmyListContract
import com.app.micaihu.view.bean.ArmyList
import com.app.utils.biz.Biz

/**
 * 未加入军团列表
 */
open class ArmyListPresenter : BasePresenter<ArmyListContract.View>(), ArmyListContract.Presenter {

    private var isRefresh = true
    private var page = 1
    private var firstLoad = true


    override fun armyList() {
        if (firstLoad) {
            getView()?.showLoading()
            firstLoad = false
        }
        val params = ParamsMapUtils.commonParams
        params["page"] = page
        params["uid"] = Biz.instance.uid()
        requestNetwork(apiService.armyList(params), object : NetRequestListener<BaseBean<ArmyList?>?> {
            override fun onSuccess(result: BaseBean<ArmyList?>?) {
                getView()?.hideLoading()
                page++
                val loadType = if (isRefresh) LoadType.TYPE_REFRESH_SUCCESS else LoadType.TYPE_LOAD_MORE_SUCCESS
                getView()?.handleArmyList(result, loadType)
            }

            override fun onFailed(e: Throwable?) {
                getView()?.hideLoading()
                val loadType = if (isRefresh) LoadType.TYPE_REFRESH_ERROR else LoadType.TYPE_LOAD_MORE_ERROR
                getView()?.handleArmyList(null, loadType)
                getView()?.onError(e)
            }
        })
    }

    override fun refresh() {
        page = 1
        isRefresh = true
        armyList()
    }

    override fun loadMore() {
        isRefresh = false
        armyList()
    }


    override fun refreshArmyList() {
        isRefresh = true
        val params = ParamsMapUtils.commonParams
        params["page"] = 1
        params["uid"] = Biz.instance.uid()
        requestNetwork(apiService.armyList(params), object : NetRequestListener<BaseBean<ArmyList?>?> {
            override fun onSuccess(result: BaseBean<ArmyList?>?) {
                getView()?.hideLoading()
                val loadType = if (isRefresh) LoadType.TYPE_REFRESH_SUCCESS else LoadType.TYPE_LOAD_MORE_SUCCESS
                getView()?.handleArmyList(result, loadType)
            }

            override fun onFailed(e: Throwable?) {
                getView()?.hideLoading()
                val loadType = if (isRefresh) LoadType.TYPE_REFRESH_ERROR else LoadType.TYPE_LOAD_MORE_ERROR
                getView()?.handleArmyList(null, loadType)
                getView()?.onError(e)
            }
        })
    }

}